<template>
  <n-modal
    v-model:show="showDialog"
    preset="dialog"
    class="rounded-[24px]"
    title=""
    :show-icon="false"
    style="width: 700px"
  >
    <div>
      <div class="text-[18px] mb-[16px] font-[500] text-center">
        {{ $t("button.添加送货地址") }}
      </div>
      <div>
        <n-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-placement="left"
          label-width="130"
        >
          <template v-if="props.type == 1">
            <n-form-item class="w-[480px]" path="fullName">
              <template #label>
                <div>Destinatarios</div>
                <div>(收件人)</div>
              </template>
              <n-input
                size="large"
                v-model:value="formData.fullName"
                :placeholder="$t('tips.输入姓名')"
              />
            </n-form-item>
            <n-form-item class="w-[380px]" path="phone">
              <template #label>
                <div>Número de contacto</div>
                <div>(收件人电话)</div>
              </template>
              <n-input
                size="large"
                v-model:value="formData.phone"
                :placeholder="$t('tips.输入电话')"
              />
            </n-form-item>
            <!-- <n-form-item
              class="w-[380px]"
              path="postCode"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.邮编`)"
            >
              <n-input
                size="large"
                v-model:value="formData.postCode"
                :placeholder="$t('tips.输入邮编')"
                @blur="onBlurPostCode"
              />
            </n-form-item> -->

            <n-form-item path="region">
              <template #label>
                <div>Región</div>
                <div>(地区)</div>
              </template>
              <n-cascader
                placeholder="省/ estado ; 市/ cuidad ; 区/ Colonia"
                size="large"
                :options="districtsOpt"
                v-model:value="formData.region"
                children-field="districts"
                check-strategy="child"
                value-field="name"
                label-field="name"
                @update:value="onUpdateValue"
              >
              </n-cascader>
            </n-form-item>
            <n-form-item path="address">
              <template #label>
                <div>Dirección detallada</div>
                <div>(详细地址)</div>
              </template>
              <n-input
                size="large"
                v-model:value="formData.address"
                :placeholder="$t('tips.输入详细地址')"
              />
            </n-form-item>
            <n-form-item path="setAsDefault" :label="$t('address.默认地址')">
              <n-checkbox v-model:checked="formData.setAsDefault"> </n-checkbox>
            </n-form-item>
          </template>
          <template v-else>
            <n-form-item
              class="w-[480px]"
              path="fullName"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.姓名`)"
            >
              <n-input
                size="large"
                v-model:value="formData.fullName"
                :placeholder="$t('tips.输入姓名')"
              />
            </n-form-item>
            <n-form-item
              class="w-[380px]"
              path="phone"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.电话`)"
            >
              <n-input
                size="large"
                v-model:value="formData.phone"
                :placeholder="$t('tips.输入电话')"
              />
            </n-form-item>
            <n-form-item
              class="w-[380px]"
              path="postCode"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.邮编`)"
            >
              <n-input
                size="large"
                v-model:value="formData.postCode"
                :placeholder="$t('tips.输入邮编')"
                @blur="onBlurPostCode"
              />
            </n-form-item>
            <div class="flex gap-[32px]">
              <div class="flex-1">
                <n-form-item
                  path="provinceText"
                  :label="$t(`address${props.type == 1 ? '.中文' : ''}.州`)"
                >
                  <n-input
                    size="large"
                    v-model:value="formData.provinceText"
                    :placeholder="$t('tips.输入州')"
                  />
                </n-form-item>
              </div>
              <div class="flex-1">
                <n-form-item
                  path="cityText"
                  :label="$t(`address${props.type == 1 ? '.中文' : ''}.城市`)"
                >
                  <n-input
                    size="large"
                    v-model:value="formData.cityText"
                    :placeholder="$t('tips.输入城市')"
                  />
                </n-form-item>
              </div>
            </div>

            <n-form-item
              path="areaText"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.区`)"
            >
              <n-input
                size="large"
                v-model:value="formData.areaText"
                :placeholder="$t('tips.输入区')"
              />
            </n-form-item>
            <n-form-item
              path="address"
              :label="$t(`address${props.type == 1 ? '.中文' : ''}.详细地址`)"
            >
              <n-input
                size="large"
                v-model:value="formData.address"
                :placeholder="$t('tips.输入详细地址')"
              />
            </n-form-item>
            <n-form-item path="setAsDefault" :label="$t('address.默认地址')">
              <n-checkbox v-model:checked="formData.setAsDefault"> </n-checkbox>
            </n-form-item>
          </template>
        </n-form>
      </div>
      <div class="flex w-[400px] m-auto gap-[16px]">
        <div class="flex-1">
          <n-button :loading="loading" type="primary" size="large" block @click="submit">
            {{ $t("button.保存") }}
          </n-button>
        </div>
        <div class="flex-1">
          <n-button type="primary" size="large" ghost block @click="showDialog = false">
            {{ $t("button.取消") }}
          </n-button>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup>
import { ref } from "vue";
import { insert, update } from "@/api/address";
import { useMessage } from "naive-ui";
import { obtenerEstadoPorCodigoPostal } from "@/utils/getMexAddress";
import { throttle } from "lodash";
import { districtsOpt } from "@/utils/city";

const showDialog = ref(false);
const formData = ref({});
const formRef = ref(null);
const message = useMessage();
const loading = ref(false);
const emit = defineEmits(["reload"]);
const props = defineProps({
  type: {
    type: Number,
    default: 0, //0墨西哥地址  1中国地址
  },
});
const rules = {
  fullName: {
    required: true,
    message: window.tt("tips.输入姓名"),
    trigger: ["input", "blur"],
  },
  phone: {
    required: true,
    message: window.tt("tips.输入电话"),
    trigger: ["input", "blur"],
  },
  postCode: {
    required: true,
    message: window.tt("tips.输入邮编"),
    trigger: ["input", "blur"],
  },
  provinceText: {
    required: true,
    message: window.tt("tips.输入州"),
    trigger: ["input", "blur"],
  },
  cityText: {
    required: true,
    message: window.tt("tips.输入城市"),
    trigger: ["input", "blur"],
  },
  areaText: {
    required: true,
    message: window.tt("tips.输入区"),
    trigger: ["input", "blur"],
  },
  address: {
    required: true,
    message: window.tt("tips.输入详细地址"),
    trigger: ["input", "blur"],
  },
  region: {
    required: true,
    message: window.tt("tips.输入区"),
    trigger: ["input", "blur"],
  },
};
const open = (data) => {
  formData.value = {};
  showDialog.value = true;

  if (data) {
    formData.value = data;
    formData.value.region = data.areaText; //级联需要
    formData.value.setAsDefault = formData.value.status == 0 ? true : false;
  }
};

const onBlurPostCode = () => {
  if (props.type == 0) {
    if (formData.value.postCode.length > 2) {
      formData.value.provinceText = obtenerEstadoPorCodigoPostal(formData.value.postCode);
    }
  }
};

const submit = throttle(async (e) => {
  e.preventDefault();
  formRef.value?.validate(async (errors) => {
    if (!errors) {
      loading.value = true;
      formData.value.status = formData.value.setAsDefault ? 0 : 1;
      formData.value.type = props.type;
      // console.log("%c Line:285 🥥 formData.value", "color:#42b983", formData.value);

      // return;
      if (formData.value.id) {
        await update(formData.value);
      } else {
        await insert(formData.value);
      }
      loading.value = false;
      message.success(window.tt("tips.地址保存成功"));
      showDialog.value = false;
      emit("reload");
    } else {
      // console.log(errors);
      // message.error("验证失败");
    }
  });
}, 1000);

const onUpdateValue = (value, option, pathValues) => {
  formData.value.provinceText = pathValues[0].name;
  formData.value.cityText = pathValues[1].name;
  formData.value.areaText = pathValues[2].name;
  formData.value.postCode = pathValues[2].adcode;
  // console.log("%c Line:239 🥚 value", "color:#ed9ec7", value, option, pathValues);
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
